/*************************************************************************
*file name   :  HttpUtil.java
*copyright   :   umpay
*modified    :   Mar 18, 2011
*************************************************************************/
package com.sram.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.slf4j.Logger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.slf4j.LoggerFactory;


/*************************************************************************
 *class : HttpUtil
 *@author :  Ding Zhe
 *@version :  1.0  
 *description :  
 *@see :                        
 *************************************************************************/
public class HttpUtil {

	private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
    /** 
     * 执行一个HTTP GET请求，返回请求响应的HTML 
     * 
     * @param url                 请求的URL地址 
     * @param queryString 请求的查询参数,可以为null 
     * @param charset         字符集 
     * @param pretty            是否美化 
     * @return 返回请求响应的HTML 
     */ 
    public static String doGet(String url, String queryString, String charset, boolean pretty) { 
            StringBuffer response = new StringBuffer(); 
            HttpClient client = new HttpClient();
            HttpMethod method = new GetMethod(url);
            try { 
                    if (StringUtil.isNotEmpty(queryString))
                            //对get请求参数做了http请求默认编码，好像没有任何问题，汉字编码后，就成为%式样的字符串 
                            method.setQueryString(URIUtil.encodeQuery(queryString)); 
                    client.executeMethod(method); 
                    if (method.getStatusCode() == HttpStatus.SC_OK) { 
                            BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); 
                            String line; 
                            while ((line = reader.readLine()) != null) { 
                                    if (pretty) 
                                            response.append(line).append(System.getProperty("line.separator")); 
                                    else 
                                            response.append(line); 
                            } 
                            reader.close(); 
                    } 
            } catch (URIException e) { 
                    log.error("执行HTTP Get请求时，编码查询字符串“" + queryString + "”发生异常！", e); 
            } catch (IOException e) { 
                    log.error("执行HTTP Get请求" + url + "时，发生异常！", e); 
            } catch (Exception e) {
            	log.error("发生异常:" + e.getMessage());
			}finally { 
                    method.releaseConnection();
                    log.info("HttpUtil.doGet连接已关闭");
            } 
            return response.toString(); 
    } 

    /** 
     * 执行一个HTTP POST请求，返回请求响应的HTML 
     * 
     * @param url         请求的URL地址 
     * @param params    请求的查询参数,可以为null 
     * @param charset 字符集 
     * @param pretty    是否美化 
     * @return 返回请求响应的HTML 
     */ 
    public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) { 
            StringBuffer response = new StringBuffer(); 
            HttpClient client = new HttpClient(); 
            HttpMethod method = new PostMethod(url); 
            //设置Http Post数据 
            if (params != null) { 
                    HttpMethodParams p = new HttpMethodParams(); 
                    for (Map.Entry<String, String> entry : params.entrySet()) { 
                            p.setParameter(entry.getKey(), entry.getValue()); 
                    } 
                    method.setParams(p); 
            } 
            try { 
                    client.executeMethod(method); 
                    if (method.getStatusCode() == HttpStatus.SC_OK) { 
                            BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset)); 
                            String line; 
                            while ((line = reader.readLine()) != null) { 
                                    if (pretty) 
                                            response.append(line).append(System.getProperty("line.separator")); 
                                    else 
                                            response.append(line); 
                            } 
                            reader.close(); 
                    } 
            } catch (IOException e) { 
                    log.error("执行HTTP Post请求" + url + "时，发生异常！", e); 
            } finally { 
                    method.releaseConnection(); 
                    log.info("HttpUtil.doPost连接已关闭");
            } 
            return response.toString(); 
    } 
    /**
	 * desc:http请求
	 * <p>创建人：王世院, Oct 22, 2013 10:53:36 AM</p>
	 * @param urlstr
	 * @param stream
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Object getResObjPost(String urlstr,XStream stream,Object obj)throws Exception{
		InputStreamReader reader =null;
		HttpClient httpclient = null;
		PostMethod post = null;
		try{
			//创建httpclient
			httpclient = new HttpClient();
			//配置读超时时间
			httpclient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
			//配置连接超时时间
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(60 * 1000);
			log.info("now to send! url is " + urlstr);
			post = new PostMethod(urlstr);

			post.addRequestHeader("Content-Type", "text/xml");
			post.addRequestHeader("Charset", "UTF-8");			
			
			post.setRequestBody(new ByteArrayInputStream(stream.toXML(obj).getBytes("UTF-8")));
			int statusCode = httpclient.executeMethod(post);
			if (statusCode == HttpStatus.SC_OK) {
				log.info("接收响应ok！");
				log.info(post.getResponseBodyAsStream().toString());
				reader = new InputStreamReader(post.getResponseBodyAsStream(), "UTF-8");
				log.info("读入reader OK！");
				stream = new XStream(new DomDriver());
				obj =  stream.fromXML(reader);
				return obj;
			}else if (statusCode == HttpStatus.SC_GATEWAY_TIMEOUT) {
				log.info("接收响应超时！");
				Map<String, String> resobj = new HashMap<String, String>();
				resobj.put("retCode", String.valueOf(statusCode));
				resobj.put("retMsg", "连接目标系统超时");
				return resobj;
			}else{
				log.info("接收响应错误！");
				return null;
			}
		}catch(SocketTimeoutException se){
			log.error("连接目标系统错误",se);
			Map<String, String> resobj = new HashMap<String, String>();
			resobj.put("retCode", "9999");
			resobj.put("retMsg", "连接目标系统错误");
			return resobj;
		}catch(Exception tht){
			log.error("",tht);
			return null;
		}catch(Error er){
			log.error("",er);
			return null;			
		}finally{
			try{
				reader.close();
			}catch(Exception e){
				reader=null;
			}
			if(post != null){
				try{
					post.releaseConnection();
				}finally{
					post = null;
				}
			}
			if(httpclient != null){
				try {
					 httpclient.getHttpConnectionManager().closeIdleConnections(0);
					 log.info("HttpUtil.getResObjPost连接已关闭");
				}finally{
					httpclient = null;
				}
			}
		}
	}
	public static void main(String[] args) {
		 String y = doGet("http://10.10.38.155:9918/restUserManager/rest2/sooPayUserSearch_2/spMer0000000020/*/13426344511/*/getSfMerInfo.xml", null, "UTF8", true); 
//		 String y = doGet("http://video.sina.com.cn/life/tips.html", null, "GBK", true);
		 System.out.println(y); 
	}

	
}
